import pandas as pd
import geopandas as gpd 
import matplotlib.pyplot as plt

""" 人工校正，生成真实匹配关系 """


# 读取csv文件
df = pd.read_csv('1.csv')

contour1 = gpd.read_file('E:/Data/QGIS/2contour/HG/HG2W_CtG1.shp' ,encoding='gbk')
contour2= gpd.read_file('E:/Data/QGIS/2contour/HG/HGDEM_CtG.shp' ,encoding='gbk')


for row in df.itertuples():
    line1 = contour1.loc[contour1['myid'] == str(row.col1)].iloc[0]
    line2 =contour2.loc[contour2['myid'] == row.col2].iloc[0]


    """ 可视化 """
    # 创建画布和子图
    fig, ax = plt.subplots(figsize=(10, 8))

    # 绘制原始曲线
    gpd.GeoSeries([line1.geometry]).plot(ax=ax, color='#FF6B6B', label=row.col1, linewidth=2)  
    gpd.GeoSeries([line2.geometry]).plot(ax=ax, color='#73C2FF', label=row.col2, linewidth=5)  # 淡蓝色


    # 添加图例和标题
    ax.legend(loc='best',prop={'size': 22})
    plt.tight_layout()
    plt.show()












#利用重叠面积来获得匹配关系


""" ##构建缓冲区
road1_buffer = road1.geometry.buffer(5,cap_style=2)
road2_buffer = road2.geometry.buffer(5,cap_style=2)
road1_buffer = gpd.GeoDataFrame(road1, geometry=road1_buffer)
road2_buffer = gpd.GeoDataFrame(road2, geometry=road2_buffer)



# #Create R-tree spatial index for faster intersection checking 
road1_idx = rtree.index.Index() 
for idx, road in road1_buffer.iterrows(): 
    road1_idx.insert(idx, road.geometry.bounds) 

def find_matchline(feature2): 
    a2 = feature2.geometry 
    
    overlaps = road1_idx.intersection(a2.bounds)
    roads_list = [] 
    for idx in overlaps: 
        feature1 = road1_buffer.loc[idx] 
        a1 = feature1.geometry 
        if a2.intersects(a1): 

            overlap_area = a2.intersection(a1).area 
            if overlap_area / a2.area > 0.8 or overlap_area / a1.area> 0.8: 
                #角度约束
                line1=road1.loc[road1['myid'] == feature1.myid].iloc[0]
                line2=road2.loc[road2['myid'] == feature2.myid].iloc[0]
                # if  calculate_angle(line1.geometry ,  line2.geometry) < 40 and attribute_comparison(line1, line2)==1:
                if  attribute_comparison(line1, line2)==1:
                    roads_list.append(feature1.myid)
    if  roads_list:  
        roads_list.insert(0, feature2.myid) 
    return roads_list

# Sort features in road2_buffer by index
road2_buffer = road2_buffer.sort_index()
match_list = []
for row in road2_buffer.itertuples():
    result = find_matchline(row)
    if result:
        match_list.append(result)
# Convert the elements of the list to dataframe type and store them in a list
df_lst=[] 
for row in match_list:
    df_row = pd.DataFrame([row])
    df_lst.append(df_row)
# 使用concat函数将列表中的各个dataframe拼接成一个大的dataframe
match_df = pd.concat(df_lst, axis=0, ignore_index=True)

##dataframe to .csv
match_df.to_csv('./Match_result/AMa.csv', index=False, header=False,chunksize=1000) """